// 网络管理
class NetworkManager {
    constructor() {
        this.socket = io();
        this.currentRoomId = null;
        this.setupSocketListeners();
        
        // 立即绑定房间UI事件
        this.setupRoomUIEvents();
    }

    setupRoomUIEvents() {
        const joinButton = document.getElementById('join-button');
        const createButton = document.getElementById('create-button');
        
        if (joinButton) {
            joinButton.onclick = () => {
                const roomId = document.getElementById("room-id").value.trim();
                if (roomId) {
                    console.log('Join button clicked, roomId:', roomId);
                    this.joinRoom(roomId);
                } else {
                    alert('请输入房间ID');
                }
            };
        }
        
        if (createButton) {
            createButton.onclick = () => {
                console.log('Create button clicked');
                this.createRoom();
            };
        }
    }

    getSocketId() {
        return this.socket.id;
    }

    setupSocketListeners() {
        this.socket.on("connect", () => {
            console.log('Connected to server, socket id:', this.socket.id);
        });

        this.socket.on("joinRoomResponse", (data) => {
            console.log('Received joinRoomResponse:', data);
            if (data.success) {
                this.currentRoomId = data.roomId;
                
                // 隐藏房间UI
                const roomUI = document.getElementById("room-ui");
                if (roomUI) {
                    roomUI.style.display = "none";
                }

                // 切换到游戏场景
                go("game", { roomId: this.currentRoomId });
                
                // 创建本地玩家
                const playerData = {
                    id: this.socket.id,
                    x: Math.random() * (CONFIG.GAME.WIDTH - 100) + 50,
                    y: Math.random() * (CONFIG.GAME.HEIGHT - 100) + 50,
                    angle: 0
                };
                gameObjectManager.createPlayer(playerData);

                // 创建已存在的其他玩家
                if (data.players && Array.isArray(data.players)) {
                    data.players.forEach(player => {
                        if (player.id && player.id !== this.socket.id) {
                            const otherPlayerData = {
                                id: player.id,
                                x: player.x || Math.random() * (CONFIG.GAME.WIDTH - 100) + 50,
                                y: player.y || Math.random() * (CONFIG.GAME.HEIGHT - 100) + 50,
                                angle: player.angle || 0
                            };
                            gameObjectManager.createPlayer(otherPlayerData);
                        }
                    });
                }
                
                // 通知服务器玩家已准备就绪
                this.socket.emit("playerReady", {
                    roomId: this.currentRoomId,
                    playerId: this.socket.id,
                    ...playerData
                });
            } else {
                console.error('Failed to join room:', data.message);
                alert('加入房间失败: ' + (data.message || '未知错误'));
            }
        });

        this.socket.on("playerReady", (data) => {
            console.log('Player ready:', data);
            if (data.playerId && !gameObjectManager.getObject(data.playerId)) {
                const playerData = {
                    id: data.playerId,
                    x: data.x || Math.random() * (CONFIG.GAME.WIDTH - 100) + 50,
                    y: data.y || Math.random() * (CONFIG.GAME.HEIGHT - 100) + 50,
                    angle: data.angle || 0
                };
                gameObjectManager.createPlayer(playerData);
            }
        });

        this.socket.on("playerJoined", (data) => {
            console.log('Player joined:', data);
            if (data.id && !gameObjectManager.getObject(data.id)) {
                const playerData = {
                    id: data.id,
                    x: data.x || Math.random() * (CONFIG.GAME.WIDTH - 100) + 50,
                    y: data.y || Math.random() * (CONFIG.GAME.HEIGHT - 100) + 50,
                    angle: data.angle || 0
                };
                gameObjectManager.createPlayer(playerData);
            }
        });

        this.socket.on("playerLeft", (playerId) => {
            console.log('Player left:', playerId);
            gameObjectManager.removeObject(playerId);
        });

        this.socket.on("gameUpdate", (data) => {
            if (!data.players) return;
            
            data.players.forEach(playerData => {
                if (!playerData.id) return;
                
                const player = gameObjectManager.getObject(playerData.id);
                if (player && !player.isLocal) {
                    player.pos = vec2(playerData.x || player.pos.x, playerData.y || player.pos.y);
                    player.angle = playerData.angle || player.angle;
                }
            });
        });

        this.socket.on("bulletFired", (data) => {
            if (!data || !data.playerId) return;
            gameObjectManager.createBullet(data);
        });

        // 处理断开连接
        this.socket.on("disconnect", () => {
            console.log("Disconnected from server");
            this.currentRoomId = null;
            gameObjectManager.clear();
            const roomUI = document.getElementById("room-ui");
            if (roomUI) {
                roomUI.style.display = "block";
            }
        });

        // 处理重新连接
        this.socket.on("reconnect", () => {
            console.log("Reconnected to server");
            if (this.currentRoomId) {
                this.joinRoom(this.currentRoomId);
            }
        });
    }

    joinRoom(roomId) {
        if (!roomId) {
            console.error('No room ID provided');
            return;
        }
        
        console.log('Attempting to join room:', roomId);
        // 清理当前游戏状态
        gameObjectManager.clear();
        
        this.socket.emit("joinRoom", {
            roomId: roomId,
            playerId: this.socket.id
        });
    }

    createRoom() {
        const roomId = Math.random().toString(36).substring(2, 8);
        console.log('Creating new room:', roomId);
        document.getElementById("room-id").value = roomId;
        this.joinRoom(roomId);
    }

    emitPlayerMove(x, y, angle) {
        if (!this.currentRoomId) return;
        
        this.socket.emit("playerMove", {
            roomId: this.currentRoomId,
            x: x,
            y: y,
            angle: angle
        });
    }

    emitShoot(x, y, angle) {
        if (!this.currentRoomId) return;
        
        this.socket.emit("shoot", {
            roomId: this.currentRoomId,
            x: x,
            y: y,
            angle: angle
        });
    }

    emitBulletHit(data) {
        if (!this.currentRoomId) return;
        
        this.socket.emit("bulletHit", {
            roomId: this.currentRoomId,
            ...data
        });
    }
}

// 创建全局网络管理器实例
const networkManager = new NetworkManager(); 